package com.cloudcentral.service;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudcentral.entity.Role;
import com.cloudcentral.entity.RoleAuth;
import com.cloudcentral.entity.dto.RoleDTO;
import com.cloudcentral.entity.query.RoleQuery;
import com.cloudcentral.entity.vo.RoleVO;
import com.cloudcentral.exception.FailureException;
import com.cloudcentral.mapper.RoleAuthMapper;
import com.cloudcentral.mapper.RoleMapper;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统角色表 服务实现类
 * </p>
 *
 * @author Administrator
 * @since 2023-10-27
 */
@Slf4j
@Service
public class RoleService extends ServiceImpl<RoleMapper, Role> {
  private final RoleAuthMapper roleAuthMapper;

  @Autowired
  public RoleService(RoleAuthMapper roleAuthMapper) {
    this.roleAuthMapper = roleAuthMapper;
  }

  @Transactional(rollbackFor = {Exception.class})
  @GlobalTransactional(rollbackFor = {Exception.class})
  public Boolean submit(RoleDTO dto) throws Exception {
    if (dto.getPlatformId() == null) throw new FailureException("缺少平台ID");
    else if (StringUtils.isBlank(dto.getName())) throw new FailureException("缺少角色名称");
    else if (StringUtils.isBlank(dto.getAuthIds())) throw new FailureException("缺少权限配置");
    else {
      Role role = Role.builder()
          .id(dto.getId())
          .platformId(dto.getPlatformId())
          .name(dto.getName())
          .remark(dto.getRemark())
          .build();
      saveOrUpdate(role);
      UpdateWrapper<RoleAuth> updateWrapper = new UpdateWrapper<>();
      updateWrapper.eq("role_id", role.getId());
      roleAuthMapper.delete(updateWrapper);
      List<Long> authIds = Arrays.stream(dto.getAuthIds().split(",")).mapToLong(Long::valueOf).distinct().boxed().collect(Collectors.toList());
      roleAuthMapper.insertBatch(role.getId(), authIds);
      return true;
    }
  }

  @Transactional(rollbackFor = {Exception.class})
  @GlobalTransactional(rollbackFor = {Exception.class})
  public Boolean delete(Long id) {
    return removeById(id);
  }

  public RoleVO queryRoleVOById(Long id) {
    return baseMapper.queryRoleVOById(id);
  }

  public List<RoleVO> listRoleVO(RoleQuery query) {
    return baseMapper.listRoleVO(query);
  }
}
